package top.jnaw.jee.platform.model;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.qiniu.api.auth.AuthException;
import java.io.File;
import java.util.List;
import org.json.JSONException;
import top.jnaw.jee.platform.Consts;
import top.jnaw.jee.platform.Consts.Result;
import top.jnaw.jee.platform.model.base.BaseFiles;
import top.jnaw.jee.utils.Excel;
import top.jnaw.jee.utils.Images;
import top.jnaw.jee.utils.Log;
import top.jnaw.jee.utils.ModelResult;
import top.jnaw.jee.utils.Models;
import top.jnaw.jee.utils.qiniu.ExecuteResult;
import top.jnaw.jee.utils.qiniu.QiniuUtil;

/**
 * Generated by JFinal.
 */
@SuppressWarnings("serial")
public class Files extends BaseFiles<Files> {

  public static final top.jnaw.jee.platform.model.Files dao = new top.jnaw.jee.platform.model.Files()
      .dao();

  private static final String TYPE_OTHER = "other";
  private static final String TYPE_IMAGE = "image";
  private static final String TYPE_THEME = "theme";

  public static ModelResult add(int uid, File target, String orgName,
      String from, boolean image, String url, boolean theme) {
    ModelResult result = new ModelResult(Result.kBadCheck);

    JSONObject json = new JSONObject();
    result.setObject(json);

    String targetPath = target.getAbsolutePath();
//    String url = targetPath
//        .replace(Consts.UPLOAD_FOLDER, Consts.UPLOAD_URL_BASE);
    int range = targetPath.lastIndexOf(".");
    String suffix = " ";
    if (range != -1) {
      suffix = targetPath.substring(range);
    }
    top.jnaw.jee.platform.model.Files file = new top.jnaw.jee.platform.model.Files();
    file.setFrom(from);
    file.setFileType(image ? (theme ? TYPE_THEME : TYPE_IMAGE) : TYPE_OTHER);
    file.setName(target.getName());
    file.setOrgName(orgName);
    file.setSuffiix(suffix);
    file.setUrl(url);
    file.setUid(uid);

    if (!file.save()) {
      result.setResult(Result.kModelSaveError);
      return result;
    }

    result.setResult(Result.kSuccess);
    json.put("id", file.getId());
    json.put("url", file.getUrl());
    json.put("name", file.getOrgName());

    if (image) {
      String thumbPath = targetPath + ".thumb.jpg";

      if (!Images.thumb(targetPath, thumbPath, 128)) {
        result.setResult(Result.kImageThumbError);
        return result;
      }

      url += ".thumb.jpg";
      json.put("thumb", url);
      QiniuUtil qiniuUtil = new QiniuUtil();
      ExecuteResult<String> executeResult = null;
      try {
        executeResult = qiniuUtil.uploadFile(thumbPath);
      } catch (AuthException e) {
        e.printStackTrace();
      } catch (JSONException e) {
        e.printStackTrace();
      }
      if (null != executeResult) {
        file.setThumb(executeResult.getResult());
      }
      file.update();
    }

    result.setResult(Result.kSuccess);
    return result;
  }

  public static ModelResult list(int page, int size, String type,
      String title, int uid, int id) {
    ModelResult result = new ModelResult(Result.kBadParam);
    List<Files> list;
    String sql;
    switch (type) {
      case "theme": {
        sql = "select id, url,thumb from files where file_type='theme' order by create_time desc";
        top.jnaw.jee.platform.model.Files theme = dao.findFirst(sql);
        if (null != theme) {
          result.setObject(theme);
        } else {
          result.setObject(new JSONObject());
        }
        result.setResult(Result.kSuccess);
        break;
      }
      case "thumb": {
        sql = "select id, url,thumb from files where file_type='thumb'";
        list = dao.find(sql);
        if (null != list && list.size() > 0) {
          result.setObject(list);
        } else {
          result.setObject(new JSONArray());
        }
        result.setResult(Result.kSuccess);
        break;
      }
      case "model": {
        String sec = Db.getSql("files-model-list-sec");
        String exp = Db.getSql("files-model-list-exp");
        Page pages = Db.paginate(page, size, sec, exp, id);
        JSONObject object = Models.compressPage(pages);
        JSONArray array = object.getJSONArray("data");
        JSONArray data = new JSONArray();
        if (null != array && array.size() > 0) {
          for (int i = 0; i < array.size(); i++) {
            int fid = array.getJSONObject(i).getIntValue("appid");
            int model = array.getJSONObject(i).getIntValue("model");
            if (fid > 0 && model > 0) {
              Function function = Function.dao.findById(fid);
              if (null != function) {
                sql =
                    "select * from " + function.getDescription() + " where id="
                        + model;
                Record record = Db.findFirst(sql);
                if (null != record) {
                  record.set("model", function);
                  data.add(record.getColumns());
                }
              }
            }
          }
        }
        object.put("data", data);
        result.setObject(object);
        result.setResult(Result.kSuccess);
        break;
      }
      default:
        String sec = Db.getSql("files-list-sec");
        String exp = Db.getSql("files-list-exp");
        if (StrKit.notBlank(title)) {
          exp += " AND org_name LIKE concat('%','" + title + "', '%')";
        }
        exp += " group by f.id\n"
            + "ORDER BY f.create_time desc";
        Db.update(Db.getSql("support-full-group"));
        Page pages = Db.paginate(page, size, sec, exp, uid);
        JSONObject object = Models.compressPage(pages, true, "file");
        if (null != object) {
          result.setObject(object);
        } else {
          result.setObject(new JSONObject());
        }
        result.setResult(Result.kSuccess);
        break;
    }
    return result;
  }

  public static ModelResult query(int id) {
    ModelResult result = new ModelResult(Result.kNull);
    String sql = Db.getSql("files-list")
        .replace("f.uid =?", " f.id = " + id);
    top.jnaw.jee.platform.model.Files files = dao.findFirst(sql);
    if (null != files) {
      result.setResult(Result.kSuccess);
      result.setObject(files);
    }
    return result;
  }

  /**
   * 1.读取excel 2.获取行数据（1.获取工作簿 - 获取行数据） 3.解析array 到数据库
   */
  public static ModelResult importData(JSONObject config) {

    ModelResult result = new ModelResult(Result.kModelError);

    try {
      Excel excel = new Excel(new File("D:\\images\\部门以及人员信息.xlsx"));

//      Log.d(excel.getData().toString());

      JSONObject sheet = excel.getData().getJSONObject(0);

      JSONArray array = sheet.getJSONArray("data");
      for (int i = 0; i < array.size(); i++) {

        JSONArray userArray = array.getJSONArray(i);

        //处理数据
        boolean r = handelData(userArray, config);
        if (!r) {
          Log.i("数据格式有问题，第" + i);
          break;
        }
      }
      result.setResult(Result.kSuccess);
    } catch (Exception e) {
      e.printStackTrace();
    }

    return result;
  }

  /**
   * 根据配置 处理行数据
   */
  public static boolean handelData(JSONArray data,
      JSONObject config) {

    boolean r = false;

    try {
      JSONArray titleArray = config.getJSONArray("title");

      for (int i = 0; i < data.size(); i++) {

        for (int j = 0; j < titleArray.size(); j++) {
          if (titleArray.getJSONObject(j).getBoolean("is_handle") && data
              .getJSONObject(i).getString("title")
              .equals(titleArray.getJSONObject(j).getString("name"))) {

            data
                .getJSONObject(i)
                .put("value",
                    titleArray.getJSONObject(j).getJSONObject("handle")
                        .get(data.getJSONObject(i).get("value")));

          }

        }
        r = true;
      }
    } catch (Exception e) {
      e.printStackTrace();
    }

    return r;
  }
}
